package com.sskj.api.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.sskj.api.exception.LogicException;
import com.sskj.common.enums.ApiResponseCodeEnum;
import com.sskj.common.util.ApiResponseUtil;
import com.sskj.common.vo.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        // 构造错误信息：可以是简单字符串，也可以是结构化数据
        String errorMessage = fieldErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ApiResponseUtil.fail(ApiResponseCodeEnum.REQUEST_PARAMS_VALIDATE_FAILED, errorMessage);
    }

    @ExceptionHandler(LogicException.class)
    public ApiResponse<Object> logicException(LogicException e) {
        return ApiResponseUtil.fail(ApiResponseCodeEnum.LOGIC_EXCEPTION, e.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public ApiResponse<Object> notLoginException(NotLoginException e) {
        return ApiResponseUtil.fail(ApiResponseCodeEnum.TOKEN_INVALID_OR_EXPIRED);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ApiResponse<Object> maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        log.info("{}|{}", e.getMessage(), e.getMaxUploadSize());
        return ApiResponseUtil.fail("超出最大上传文件大小");
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<Object> exception(Exception e) {
        log.info("{}", e.getClass());
        return ApiResponseUtil.fail(e.getMessage());
    }
}
